from __future__ import absolute_import
import logging
import os
#import fnmatch
from forest.api import Command, get_tool
from forest.commands.live.buildliveimage import BuildLiveImage

logger = logging.getLogger('forest.commands.installer.buildinstallerimage')

move = get_tool('system.move')
copy = get_tool('system.copy')

class BuildInstallerImage(BuildLiveImage):
    ''' Builds a live installer image.

        Two types of image can be build. Initrd::

            forest:
              image:
                type: initrd
                destination: vmlinuz initrd.img
                exclude:
                - ./var/lib/rpm*
                - ./var/lib/yum*
                - ./boot*
                - ./home/*
                - ./tmp/*

        Or iso::

            forest:
              # build a full iso image
              image:
                embed_tree: !setting embed_tree
                # modifies the embedded trees repo to use the isos Packages dir
                modify_embed_yum_prepare: True
                type: iso # initrd, cdrom, usb
                disklabel: 'Fedora 16 Custom'
                rootlabel: Installer
                isolabel: INSTALLER
                arch: x86_64
                isolinuxcfg: isolinux.cfg
                syslinux_source: /usr/share/syslinux
                destination: forest.iso

    '''
    __register__ = 'commands.forest.Image'

    def run(self, config):
        ## HACK HACK HACK for buildliveimage
        self._config = config
        install_root = config.get_install_root()
        # create a directory for the iso
        self.args = config.get('forest.image', False)

        if not self.args:
            return

        self.exclusions = self.args.get('exclude', [])

        if self.args.get('type') == 'initrd':
            kerneldest, initdest = self.args.get('destination').split(' ')
            self.find_copy_latest_kernel_to(install_root, kerneldest)
        elif self.args.get('type') == 'iso':
            self.buildisoimage(config)

    def find_copy_latest_kernel_to(self, root, dest):
        kernels = self.findkernels(root=root)
        if not kernels:
            if not os.path.exists(dest):
                raise Exception("Couldnt find a kernel to copy from the install root. Please rebuild the root")
            return
            
        Command.SIGNAL_COMMAND_PROGRESS(self, level=logging.INFO, message="Found kernels: %s" % kernels)
        kernel = kernels[0]
        # find and copy vmlinuz to the isolinux
        copy(kernel.get('path'), dest)

    def buildisoimage(self, config):
        install_root = config.get_install_root()
        Command.SIGNAL_COMMAND_PROGRESS(self, level=logging.INFO, message='Building iso installer image...')

        self.buildisolinux(config)
        self.copysyslinux()
        self.creatediscinfo()
        self.find_copy_latest_kernel_to(install_root, os.path.join(config.get_build_root(), 'isoroot', 'isolinux', 'vmlinuz'))
        self.buildiso()

    def buildbootableimage(self):

        isoroot = self.get_iso_root()

        installtreesize = self.get_size(isoroot)
        fssize = 10 * (1024*1024) + installtreesize

        get_tool('image.mkext4image')(isoroot, self.args.get('destination'), size=fssize, label=self.args.get('rootlabel','root'))
